package controller;

import domain.Role;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import services.RoleService;
import services.UserService;
import utils.PageBean;
import utils.Transform;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@SessionAttributes(value = {"loginUser"})
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * 根据条件分页查询用户信息
     * @param request
     * @return
     */
    @RequestMapping("/queryUser.action")
    public String queryUserByPage(HttpServletRequest request){
        List<User> userList1 = null;
        List<Role> roleList = null;
        PageBean pageBean = new PageBean();

        String userName = request.getParameter("queryName");
        String userRole = request.getParameter("queryUserRole");
        String currentPage = request.getParameter("pageIndex");

        if(userRole == null){
            userRole = "0";
        }
        if(currentPage == null){
            currentPage = "1";
        }
        pageBean.setCurrentPage(Integer.parseInt(currentPage));
        //调用业务接口
            userList1 = userService.queryUserByPage(userName,Integer.parseInt(userRole),pageBean);
            roleList = roleService.getAll();
            userService.totalCount(pageBean);

            request.setAttribute("totalPageCount",pageBean.getTotalPage());
            request.setAttribute("totalCount",pageBean.getTotal());
            request.setAttribute("currentPageNo",pageBean.getCurrentPage());
            request.setAttribute("queryUserName",userName);
            request.setAttribute("queryUserRole",userRole);
            request.setAttribute("userList1",userList1);
            request.setAttribute("roleList",roleList);

        return "../jsp/userlist.jsp";
    }

    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/login.action")
    public ModelAndView userLogin(HttpServletRequest request){
        String userCode = request.getParameter("userCode");
        String userPassword = request.getParameter("userPassword");
        User loginUser = null;
        ModelAndView mv = new ModelAndView();
        if(userCode!=null&&userPassword!=null){
            loginUser = userService.login(userCode,userPassword);
        }
        if(loginUser!= null){//登录成功
            //转发
            mv.addObject("loginUser",loginUser);
            mv.setViewName("forward:/jsp/frame.jsp");
        }else{//登录失败
            mv.addObject("userCode",userCode);
            mv.addObject(userPassword,userPassword);
            mv.addObject("error","用户名或密码错误！");
            //转发回登录页面
            mv.setViewName("forward:/login.jsp");
        }
        return mv;
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("/logOut.action")
    public String logOut(HttpServletRequest request){
        //删除用户session
        request.getSession().removeAttribute("loginUser");
        //返回登录页面
        return "/login.jsp";
    }

    /**
     * ajax检查旧密码是否正确
     * @param request
     * @return
     */
    @RequestMapping("/checkOldPassword.action")
    @ResponseBody
    public Object checkOldPassword(HttpServletRequest request){
        String oldPassword = request.getParameter("oldPassword");
        HashMap<String,String> result = new HashMap<>();
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(oldPassword == null){
            result.put("result","error");
        }else{
            if(loginUser == null){
                //用户session过期
                result.put("result","sessionError");
            }else{
                if(oldPassword.equals(loginUser.getUserPassword())){
                    //旧密码输入正确
                    result.put("result","true");
                }else if(!oldPassword.equals(loginUser.getUserPassword())){//旧密码输入错误
                    result.put("result","false");
                }
            }
        }
        return result;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping("/modifyPassword.action")
    public ModelAndView modifyPassword(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        User user = (User) request.getSession().getAttribute("loginUser");
        System.out.println(user.getId());
        mv.addObject("oldPassword",oldPassword);
        mv.addObject("newPassword",newPassword);
        boolean flag = userService.modifyPassword(user.getId(),newPassword);
        if(flag){
            mv.addObject("message","密码修改成功");
        }else{
            mv.addObject("message","密码修改失败");
        }
        mv.setViewName("forward:/jsp/pwdmodify.jsp");
        return mv;
    }

    /**
     * 添加用户
     * @param request
     * @return
     */
    @RequestMapping("/addUser.action")
    public String addUser(HttpServletRequest request){
        boolean flag  = false;
        //封装User
        User user = new User();
        Map<String,String[]> map = request.getParameterMap();
        Transform.beanUtilsConvert();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        flag = userService.addUser(user);
        if(flag){
            //插入成功
            request.setAttribute("message","添加成功！");
        }else{
            //插入失败
            request.setAttribute("message","添加失败!");
        }
        return "forward:../jsp/useradd.jsp";
    }

    /**
     * 检查新加用户编码是否可用
     * @param request
     * @return
     */
    @RequestMapping("/checkUserCode.action")
    @ResponseBody
    public Object checkUserCode(HttpServletRequest request){
        String userCode = request.getParameter("userCode");
        HashMap<String,String> map = new HashMap<>();
        boolean flag = userService.checkUserCode(userCode);
        if(!flag){
            map.put("userCode","exist");
        }else {
            map.put("userCode","noExist");
        }
        return map;
    }

    /**
     * 删除用户
     * @param request
     * @return
     */
    @RequestMapping("/deleteUser.action")
    @ResponseBody
    public Object deleteUser(HttpServletRequest request){
        boolean flag1 = false; //删除结果
        String id = request.getParameter("uid");
        HashMap<String,String> map = new HashMap<>();
        flag1 = userService.deleteUser(Integer.parseInt(id));
        User user = userService.queryUserById(Integer.parseInt(id));
        //判断用户是否存在
        if(user!=null){ //存在
            if(flag1){ //删除成功
                map.put("message","true");
            }else{ //删除失败
                map.put("message","false");
            }
        }else{
            map.put("message","notexist");
        }
        return map;
    }

    /**
     * 查看用户
     * @param request
     * @return
     */
    @RequestMapping("/viewUser.action")
    public String viewUser(HttpServletRequest request){
        String id = request.getParameter("uid");
        String method = request.getParameter("method");
        String path = "";
        User user = userService.queryUserById(Integer.parseInt(id));
        if(user!=null){
            request.setAttribute("user",user);
        }
        if(method.equals("view")){
            path = "forward:/jsp/userview.jsp";
        }else if(method.equals("modify")){
            path = "forward:/jsp/usermodify.jsp";
        }
        return path;
    }

    /**
     * 修改用户
     * @param request
     * @return
     */
    @RequestMapping("/updateUser.action")
    public String updateUser(HttpServletRequest request){
        boolean flag = false;
        User user = new User();
        Map<String,String[]> params = request.getParameterMap();
        Transform.beanUtilsConvert();
        try {
            BeanUtils.populate(user,params);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        flag = userService.updateUser(user);
        if(flag){
            //修改成功
            request.setAttribute("message","true");
        }else{
            request.setAttribute("message","false");
        }
        request.setAttribute("user",user);
        return "forward:/jsp/usermodify.jsp";
    }
}
